<script lang="ts" setup>
import { useUserTracking } from "./composables/useUserTracking"

// 使用业务逻辑
const {
  loading,
  searchKeyword,
  typeFilter,
  statusFilter,
  activityFilter,
  versionFilter,
  paginatedUsers,
  userTypeOptions,
  statusOptions,
  activityOptions,
  versionOptions,
  statsCards,
  headerButtons,
  currentPage,
  pageSize,
  total,
  getVersionDisplay,
  getUserTagInfo,
  isPublishLimitReached,
  getPublishInfo,
  handlePageChange,
  handleSizeChange
} = useUserTracking()

// 用户设置弹窗状态
const showUserSettingsDialog = ref(false)
const currentUser = ref<any>(null)

// 禁用弹窗状态
const showDisableDialog = ref(false)
const disableTargetUser = ref<any>(null)

// 打开用户设置弹窗
function openUserSettings(user: any) {
  currentUser.value = user
  showUserSettingsDialog.value = true
}

function openDisableDialog(user: any) {
  disableTargetUser.value = user
  showDisableDialog.value = true
}

function handleDisableConfirm(_: { reason: string }) {
  // 模拟更新为异常状态
  if (disableTargetUser.value) {
    disableTargetUser.value.accountStatus = "异常"
    ElMessage.success("已禁用用户")
  }
  showDisableDialog.value = false
}
</script>

<template>
  <div class="app-container">
    <div class="page-content">
      <!-- 页面头部 -->
      <PageHeader
        title="用户追踪看板"
        subtitle="追踪所有用户的全链路行为数据，包括试用用户和付费用户"
        :buttons="headerButtons"
      />

      <!-- 统计卡片 -->
      <StatsCards :cards="statsCards" :loading="loading" />

      <!-- 搜索和筛选区域 -->
      <div class="filter-section">
        <div class="search-box">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索品牌名称、手机号、邀请码或代理商..."
            clearable
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>

        <div class="filter-controls">
          <el-select
            v-model="typeFilter"
            placeholder="全部类型"
            style="width: 120px"
          >
            <el-option
              v-for="option in userTypeOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>

          <el-select
            v-model="statusFilter"
            placeholder="全部状态"
            style="width: 120px"
          >
            <el-option
              v-for="option in statusOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>

          <el-select
            v-model="activityFilter"
            placeholder="全部状态"
            style="width: 120px"
          >
            <el-option
              v-for="option in activityOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>

          <el-select
            v-model="versionFilter"
            placeholder="全部版本"
            style="width: 140px"
          >
            <el-option
              v-for="option in versionOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </div>
      </div>

      <!-- 用户行为追踪表格 -->
      <div class="table-section">
        <div class="table-header">
          <h3>用户行为追踪</h3>
        </div>

        <el-table
          :data="paginatedUsers"
          :loading="loading"
          style="width: 100%"
          class="user-tracking-table"
        >
          <!-- 用户信息 -->
          <el-table-column label="用户信息" min-width="200">
            <template #default="{ row }">
              <div class="user-info">
                <div class="brand-name">{{ row.nickname }}</div>
                <div class="phone-number">{{ row.phone }}</div>
                <div class="time-info">
                  <div class="register-time">注册时间：{{ row.registrationTime }}</div>
                  <div class="redeem-time">兑换时间：{{ row.lastActiveTime }}</div>
                </div>
              </div>
            </template>
          </el-table-column>

          <!-- 用户类型 -->
          <el-table-column label="用户类型" min-width="155">
            <template #default="{ row }">
              <div class="user-type-cell">
                <!-- 主要用户类型标签 -->
                <CustomTag
                  :text="getUserTagInfo(row).text"
                  :type="getUserTagInfo(row).type"
                  :icon="getUserTagInfo(row).icon"
                  size="medium"
                />

                <!-- 版本标签 -->
                <div v-if="row.userType === 0 && getVersionDisplay(row.version)" class="version-tags">
                  <CustomTag
                    :text="getVersionDisplay(row.version)?.text || ''"
                    :type="getVersionDisplay(row.version)?.type || 'default'"
                    size="medium"
                  />
                </div>
              </div>
            </template>
          </el-table-column>

          <!-- 邀请码/试用信息 -->
          <el-table-column label="邀请码/试用信息" min-width="280">
            <template #default="{ row }">
              <div class="invitation-info">
                <!-- 邀请码信息 -->
                <div v-if="row.invitationCode" class="invitation-code">{{ row.invitationCode }}</div>
                <div v-if="row.agentPath" class="agent-path">{{ row.agentPath }}</div>

                <!-- 试用期信息 -->
                <div v-if="row.userType === 1 && row.trialDaysRemaining !== undefined" class="trial-info">
                  <CustomTag
                    :text="row.trialDaysRemaining > 0 ? `剩余: ${row.trialDaysRemaining}天` : '已过期'"
                    icon="Clock"
                    :type="row.trialDaysRemaining > 0 ? 'warning' : 'danger'"
                    size="small"
                  />
                </div>

                <!-- 今日发布信息 -->
                <div class="today-publish">
                  每日限制: {{ row.dailyLimit }}条视频
                  <br>
                  今日已发布: {{ row.todayData.published }}/{{ row.dailyLimit }}
                  <CustomTag
                    v-if="isPublishLimitReached(row)"
                    text="已达上限"
                    type="danger"
                    size="small"
                  />
                </div>
              </div>
            </template>
          </el-table-column>

          <!-- 绑定账号 -->
          <el-table-column label="绑定账号" width="160">
            <template #default="{ row }">
              <div class="bind-info">
                <div class="account-item">
                  <span class="platform-label">抖音:</span>
                  <span class="account-name">{{ row.bindPhone }}</span>
                </div>
                <div class="account-item">
                  <span class="platform-label">小红书:</span>
                  <span class="account-name">{{ row.xiaohongshuAccount || row.bindPhone }}</span>
                </div>
              </div>
            </template>
          </el-table-column>

          <!-- 今日数据 -->
          <el-table-column label="今日数据" width="100">
            <template #default="{ row }">
              <div class="today-data">
                <div class="data-row">生成: {{ row.todayData.posts }}</div>
                <div class="data-row">
                  发布: {{ getPublishInfo(row).published }}
                  <span v-if="getPublishInfo(row).showLimit" class="limit-text">(限{{ getPublishInfo(row).limit }})</span>
                </div>
              </div>
            </template>
          </el-table-column>

          <!-- 累计数据 -->
          <el-table-column label="累计数据" width="100">
            <template #default="{ row }">
              <div class="total-data">
                <div class="data-row">生成: {{ row.totalData.posts }}</div>
                <div class="data-row">发布: {{ row.totalData.published }}</div>
              </div>
            </template>
          </el-table-column>

          <!-- 账户状态 -->
          <el-table-column label="账户状态" min-width="120">
            <template #default="{ row }">
              <div class="account-status">
                <CustomTag
                  :text="row.accountStatus === '正常' ? '正常' : '异常'"
                  :type="row.accountStatus === '正常' ? 'success' : 'danger'"
                  size="medium"
                />
                <CustomTag
                  :text="row.isActive ? '活跃' : '不活跃'"
                  :type="row.isActive ? 'success' : 'danger'"
                  size="medium"
                />
              </div>
            </template>
          </el-table-column>

          <!-- 最后活跃 -->
          <el-table-column label="最后活跃" width="140">
            <template #default="{ row }">
              <div class="last-active-time">{{ row.lastActiveTime }}</div>
            </template>
          </el-table-column>

          <!-- 操作 -->
          <el-table-column label="操作" width="140" fixed="right">
            <template #default="{ row }">
              <div class="action-buttons">
                <el-button
                  link
                  size="small"
                  type="primary"
                  title="设置专属模板"
                  v-if="row.userType === 0"
                  @click="openUserSettings(row)"
                >
                  <el-icon><Setting /></el-icon>
                </el-button>
                <el-button
                  link
                  size="small"
                  type="danger"
                  title="禁用用户"
                  @click="openDisableDialog(row)"
                  class="disable-btn"
                >
                  <SvgIcon name="disable" class="disable-icon" />
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination-section">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :small="false"
            :disabled="loading"
            :background="true"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handlePageChange"
          />
        </div>
      </div>
    </div>

    <!-- 用户设置弹窗 -->
    <UserSettingsDialog
      v-model="showUserSettingsDialog"
      :user="currentUser"
    />

    <!-- 禁用用户弹窗 -->
    <DisableUserDialog
      v-model="showDisableDialog"
      :user="disableTargetUser"
      @confirm="handleDisableConfirm"
    />
  </div>
</template>

<style lang="scss" scoped>
@import "./styles/index.scss";
</style>
